var express = require("express");
var router = express.Router();
const { find, save, Pack, removeData } = require("./database");
/* GET home page. */
let id = 0;
router.post("/", async function (req, res, next) {
  let list = await find("_id>=0");
  list.forEach((item) => {
    id = Math.max(id, item._id);
  });
  id++;
  let data = await find(`accountName===${req.body.email}`);
  let regEmail = new RegExp(
    /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  );
  let regPassword = new RegExp(
    /^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*? ])\S*$/
  );
  if (data.length !== 0) {
    res.send({ result: false, reason: "EMAIL REPEAT" });
  } else {
    if (!regEmail.test(req.body.email)) {
      res.send({ result: false, reason: "EMAIL ILLEGAL" });
      return;
    }
    if (!regPassword.test(req.body.password)) {
      res.send({
        result: false,
        reason:
          "The password is not strong enough, please include at least one uppercase letter, one lowercase letter, one number and one special character, and the password is at least 6 digits",
      });
      return;
    }
    await save(
      new Pack({
        _id: id,
        accountName: req.body.email,
        passWord: req.body.password,
        online: false,
      })
    );
    res.send({ result: true });
  }
});

module.exports = router;
